package myBlockingQueue;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.concurrent.*;

public class Demo {
    public static void main(String[] args) throws UnknownHostException {
        // method1();

        // method2();

        // method3();

        // method4();

        // method5();




    }

    private static void method5() throws UnknownHostException {
        // 通过InetAddress的静态方法创建对象
        InetAddress address = InetAddress.getByName("DESKTOP-U1PG1Q4");

        // 获取该对象的主机名
        String hostname = address.getHostName();

        // 获取该对象的IP地址
        String hostAddress = address.getHostAddress();

        System.out.println("hostname: " + hostname);
        System.out.println("hostAddress: " + hostAddress);
    }

    private static void method4() {
    /*DAYS
    时间单位代表二十四小时
    HOURS
    时间单位代表六十分钟
    MICROSECONDS
    时间单位代表千分之一毫秒
    MILLISECONDS
    时间单位为千分之一秒
    MINUTES
    时间单位代表60秒
    NANOSECONDS
    时间单位代表千分之一千分之一
    SECONDS
    时间单位代表一秒
    */
        /*
        Executors.defaultThreadFactory() : 返回用于创建新线程的默认线程工厂。 */
        /*
        * ThreadPoolExecutor.AbortPolicy() : 被拒绝的任务的处理程序，抛出一个 RejectedExecutionException 。
         */
        ThreadPoolExecutor pool = new ThreadPoolExecutor(
                1,
                2,
                1,
                TimeUnit.SECONDS,
                new ArrayBlockingQueue<>(10),
                Executors.defaultThreadFactory(),
                new ThreadPoolExecutor.AbortPolicy());

        pool.submit(new MyRunnable());
        pool.submit(new MyRunnable());

        pool.shutdown();
    }

    private static void method3() {
        // 参数表示线程池中的最大值，而不是初始值
        ExecutorService executorService = Executors.newFixedThreadPool(2);

        ThreadPoolExecutor pool = (ThreadPoolExecutor) executorService;
        System.out.println(pool.getPoolSize()); // 打印线程池中存在的线程数量

        executorService.submit(() -> {
            System.out.println(Thread.currentThread().getName() + "执行了");
        });

        System.out.println(pool.getPoolSize()); // 打印线程池中存在的线程数量

        executorService.shutdown();
    }

    private static void method2() {
        // 创建一个线程池对象，默认此线程池时空的，默认可以容纳int的最大值
        ExecutorService executorService = Executors.newCachedThreadPool();
        // Executors 可以帮我们创建线程池对象。
        // ExecutorService 可以帮助我们控制线程池对象。

        executorService.submit(() -> {
            System.out.println(Thread.currentThread().getName() + "执行了");
        });

        executorService.submit(() -> {
            System.out.println(Thread.currentThread().getName() + "执行了");
        });

        executorService.shutdown(); // 停止线程池
    }

    private static void method1() {
        // 创建一个阻塞队列
        ArrayBlockingQueue<String> list = new ArrayBlockingQueue<>(1);

        Foodie f = new Foodie(list);
        Cooker c = new Cooker(list);

        f.start();
        c.start();
    }
}
